package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.api.dine.DineConfigApi;
import cn.iocoder.yudao.module.api.dine.vo.DineConfigVO;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderTypeEnum;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.order.service.TradeOrderQueryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 点餐订单的 {@link TradeOrderHandler} 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Component
public class DineOrderHandler implements TradeOrderHandler {
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;

    @Resource
    private DineConfigApi dineConfigApi;

    @Override
    public void beforeOrderCreate(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if (!(Objects.equals(order.getType(), TradeOrderTypeEnum.FOOD.getType())
              || Objects.equals(order.getType(), TradeOrderTypeEnum.TAKE_AWAY.getType()))) {
            // 不是美食订单，无需继续进行接单量及主食校验
            return;
        }
        int todayOrderCount = tradeOrderQueryService.getTodayOrderCount(order.getShopId(), TradeOrderTypeEnum.TAKE_AWAY.getType());
        DineConfigVO dineConfig = dineConfigApi.getDetail(order.getShopId());
        if (dineConfig.getMaxDailyOrders() > 0) {
            Assertions.isTrue(dineConfig.getMaxDailyOrders() > todayOrderCount, "今日外卖接单量已达上限，明日再来吧");
        }
    }

}
